package com.kfh.ybracelet.my;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.adapter.AboutBabyCountAdapter;
import com.kfh.ybracelet.base.BaseActivity;
import com.kfh.ybracelet.bean.BabyDetailsResult;
import com.kfh.ybracelet.bean.UploadBean;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.AbDateUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.widget.ActionSheetDialog;
import com.kfh.ybracelet.widget.CircleImageView;
import com.kfh.ybracelet.widget.ListViewForScrollView;
import com.kfh.ybracelet.widget.MyDatePicker;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 宝宝详情页面
 * <p/>
 * Created by Administrator on 2015/8/12.
 */
public class BabyDetailsActivity extends BaseActivity {

    private List<BabyDetailsResult.KeepEntity> aboutDatas = new ArrayList<>();
    private TextView tv_name;
    private TextView tv_sex;
    private TextView tv_birthday;
    private CircleImageView babyphonto;
    private Intent mIntent;
    private ListViewForScrollView lv_aboutlist;
    public final String IMAGE_UNSPECIFIED = "image/*";
    private TextView tv_tel;
    private TextView tv_invite_code;
    //    private TextView tv_family_info;
    private String id; //孩子的id
    private String classInfo;
    private String imageUrl;
    private BabyDetailsResult.DataEntity babyDetailsData;
    /*相册选择的code*/
    private static final int PHOTO_ALBUM_CODE = 1041;
    /*拍照的code*/
    private static final int TAKE_PHOTO_CODE = 1042;
    public static final int PHOTO_RESOULT = 1043;
    /*拍照的文件保存的位置*/
    private File currentFile;

    private boolean canModify = false; //是否可修改宝宝的信息(管理员才可以修改宝宝的信息)

    //    private ProgressDialog pdialog;
    private AboutBabyCountAdapter aboutBabyCountAdapter;
//    private ScrollView sv;
    //    private ImageView iv_arr;
//    private ImageView iv_arr_name;
//    private ImageView iv_arr_sex;
//    private ImageView iv_arr_birthday;
//    private ImageView iv_arr_family;
    //    private int level;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_baby_details);

        id = getIntent().getStringExtra("id");
        classInfo = getIntent().getStringExtra("classInfo");
//        level = getIntent().getIntExtra("level", 0);

        EventBus.getDefault().register(this);

        initWidget();

    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    public void getData() {

        JSONObject j = new JSONObject();
        j.put("id", id);
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("获取中...", this, Constant.WEB_ROOT + Constant.GETCHILDINFO, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {
                            BabyDetailsResult result = JSONObject.parseObject(str, BabyDetailsResult.class);

//                            if (result.code == Constant.STATUS_SUCCESS) {

                                if (result.data != null) {
                                    babyDetailsData = result.data;

                                    setData();
                                }
                                if (result.keep != null && result.keep.size() > 0) {
                                    aboutDatas.clear();
                                    aboutDatas = result.keep;
                                    aboutBabyCountAdapter.setData(aboutDatas);
                                    //设置我的等级
//                            int mylevel = babyDetailsResult.mylevel;
                                    aboutBabyCountAdapter.setMyLevel(result.mylevel);
                                    aboutBabyCountAdapter.notifyDataSetChanged();
//                            setData();
                                  //如果是管理员权限,则可以修改宝宝信息
                                    canModify = (Constant.POWER_ADMIN == result.mylevel);

                                }

//                            } else {
//                                showToast(Constant.showErrorMsg(result.code, BabyDetailsActivity.this));
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mApplication.cancelPendingRequests(getClass().getName());

        EventBus.getDefault().unregister(this);
    }

    private void setData() {

        if (babyDetailsData != null) {
            tv_name.setText(CommonUtils.isNull(babyDetailsData.childName) ? "" : babyDetailsData.childName);
            tv_sex.setText(CommonUtils.isNull(babyDetailsData.sex) ? "男" : babyDetailsData.sex);
            tv_birthday.setText(CommonUtils.isNull(babyDetailsData.birthDay) ? "" : babyDetailsData.birthDay);
            tv_tel.setText(CommonUtils.isNull(babyDetailsData.phoneNum) ? " " : babyDetailsData.phoneNum);
            tv_invite_code.setText(CommonUtils.isNull(classInfo) ? "" : classInfo);

            Glide.with(this)
                    .load(babyDetailsData.picUrl)
                    .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                    .placeholder(R.mipmap.temp_pic)
                    .into(babyphonto);

        }
    }

    public void onEventMainThread(BabyDetailsResult.DataEntity babyInfo) {
        babyDetailsData = babyInfo;
        setData();
    }

    //    private RelativeLayout rl_family;
    private void initWidget() {

        lv_aboutlist = (ListViewForScrollView) findViewById(R.id.lv_aboutlist);

        View headView = View.inflate(this, R.layout.head_baby_detail, null);

        lv_aboutlist.addHeaderView(headView);

        RelativeLayout rl_head_pic = (RelativeLayout) headView.findViewById(R.id.rl_head_pic);
        RelativeLayout rl_name = (RelativeLayout) headView.findViewById(R.id.rl_name);
        RelativeLayout rl_sex = (RelativeLayout) headView.findViewById(R.id.rl_sex);
        RelativeLayout rl_birthday = (RelativeLayout) headView.findViewById(R.id.rl_birthday);
        RelativeLayout rl_family = (RelativeLayout) headView.findViewById(R.id.rl_family);

        tv_name = (TextView) headView.findViewById(R.id.tv_name);
        tv_sex = (TextView) headView.findViewById(R.id.tv_sex);
        tv_birthday = (TextView) headView.findViewById(R.id.tv_birthday);
        tv_tel = (TextView) headView.findViewById(R.id.tv_tel);
        tv_invite_code = (TextView) headView.findViewById(R.id.tv_invite_code);
        babyphonto = (CircleImageView) headView.findViewById(R.id.babyphonto);

//         RelativeLayout rl_head_pic = (RelativeLayout) findViewById(R.id.rl_head_pic);
//        RelativeLayout rl_name = (RelativeLayout) findViewById(R.id.rl_name);
//        RelativeLayout rl_sex = (RelativeLayout) findViewById(R.id.rl_sex);
//        RelativeLayout rl_birthday = (RelativeLayout) findViewById(R.id.rl_birthday);
//        RelativeLayout rl_family = (RelativeLayout) findViewById(R.id.rl_family);
//
//        tv_name = (TextView) findViewById(R.id.tv_name);
//        tv_sex = (TextView) findViewById(R.id.tv_sex);
//        tv_birthday = (TextView) findViewById(R.id.tv_birthday);
//        tv_tel = (TextView) findViewById(R.id.tv_tel);
//        tv_invite_code = (TextView) findViewById(R.id.tv_invite_code);
//        babyphonto = (CircleImageView) findViewById(R.id.babyphonto);
//
//        tv_family_info = (TextView) findViewById(R.id.tv_family_info);

        ImageView tv_left = (ImageView) findViewById(R.id.iv_left);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("详情");

        tv_left.setOnClickListener(this);

        rl_head_pic.setOnClickListener(BabyDetailsActivity.this);
        rl_name.setOnClickListener(BabyDetailsActivity.this);
        rl_sex.setOnClickListener(BabyDetailsActivity.this);
        rl_birthday.setOnClickListener(BabyDetailsActivity.this);
//        tv_right.setOnClickListener(this);
        rl_family.setOnClickListener(BabyDetailsActivity.this);

        aboutBabyCountAdapter = new AboutBabyCountAdapter(this, aboutDatas, id);
        lv_aboutlist.setAdapter(aboutBabyCountAdapter);
    }

    @Override
    public void widgetClick(View v) {

        switch (v.getId()) {
            case R.id.iv_left:
                finish();
                break;

            case R.id.rl_name:

                if (!canModify) {
                    showToast("权限不够");
                    return;
                }

                mIntent = new Intent(this, BabyModifyNameActivity.class);
                mIntent.putExtra("id", id);
                mIntent.putExtra("babyInfo", babyDetailsData);
                startActivity(mIntent);
                break;

            case R.id.rl_sex:

                if (!canModify) {
                    showToast("权限不够");
                    return;
                }

                mIntent = new Intent(this, BabyModifySexActivity.class);
                mIntent.putExtra("id", id);
                mIntent.putExtra("babyInfo", babyDetailsData);
                startActivity(mIntent);
                break;

            case R.id.rl_birthday:

                if (!canModify) {
                    showToast("权限不够");
                    return;
                }

                //选择生日
//                String birthday = CommonUtils.isNull(tv_birthday.getText().toString().trim()) ? "" : tv_birthday.getText().toString().trim();
                Date date = null;

                if (!CommonUtils.isNull(tv_birthday.getText().toString().trim())) {
                    date = AbDateUtil.getDateByFormat(tv_birthday.getText().toString().trim(), AbDateUtil.DATEFORMATYMD);
                }

                Calendar c = Calendar.getInstance();
                if (date != null) {
                    c.setTime(date);
                }

                new MyDatePicker(this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {

                        String month = (monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1) : (monthOfYear + 1) + "";
                        String day = dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth + "";

                        tv_birthday.setText(year + "-" + month + "-" + day);
                        updateChildInfo();
                    }

                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                        c.get(Calendar.DAY_OF_MONTH)).show();

                break;
            case R.id.rl_head_pic:

                if (!canModify) {
                    showToast("权限不够");
                    return;
                }

                showChoose();

                break;
            case R.id.rl_family: //家庭信息

                if (!canModify) {
                    showToast("权限不够");
                    return;
                }

                mIntent = new Intent(this, FamilyDetailsActivity.class);
                mIntent.putExtra("childId", id);
                mIntent.putExtra("level", getIntent().getIntExtra("level", 0));
                startActivity(mIntent);
                break;
        }
    }

    /**
     * 弹出选择照片的对话框
     */
    @Deprecated
    protected void showChoose() {

        new ActionSheetDialog(this)
                .builder()
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .addSheetItem("拍照", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 拍照
                                getTakePhoto();

                            }

                        })
                .addSheetItem("去相册选择", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                // 从相册中选择
                                getFromPhotoAlbum();
                            }
                        }).show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case TAKE_PHOTO_CODE:       //拍照

                //上传图片
                if (currentFile != null && currentFile.exists()) {
//                    pdialog = ProgressDialog.show(this, "", "图片上传中...");
//                    loadPicToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(currentFile.getPath())), currentFile.getPath());
                    startPhotoZoom(Uri.fromFile(currentFile));
                }

                break;

            case PHOTO_ALBUM_CODE:       //选择照片

                if (data == null)
                    return;

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String picturePath = cursor.getString(columnIndex);
                cursor.close();
                startPhotoZoom(Uri.fromFile(new File(picturePath)));
//                pdialog = ProgressDialog.show(this, "", "图片上传中...");
//
//                loadPicToNet(CommonUtils.compressByte(CommonUtils.getBitmapFromPath(picturePath)), picturePath);
                break;

            case PHOTO_RESOULT: //裁剪图片

                Bundle extras = data.getExtras();
                if (extras != null) {

                    Bitmap photo = extras.getParcelable("data");
                    getUploadToken(CommonUtils.compressByte(photo));

                }

                break;
        }

    }

    private void getUploadToken(final byte[] bytes) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("加载中...", this, Constant.WEB_ROOT + Constant.UPLOADTOKEN,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        LogUtil.e("tag", "返回的token==" + str);

                        final UploadBean uploadBean = JSONObject.parseObject(str, UploadBean.class);

//                        if (uploadBean.code == Constant.STATUS_SUCCESS) {

                            UploadManager uploadManager = new UploadManager();

                            uploadManager.put(bytes, uploadBean.path, uploadBean.token,
                                    new UpCompletionHandler() {
                                        @Override
                                        public void complete(String s, ResponseInfo responseInfo, org.json.JSONObject jsonObject) {

                                            //  res 包含hash、key等信息，具体字段取决于上传策略的设置。
                                            Log.e("qiniu", s + ",\r\n " + responseInfo + ",\r\n " + jsonObject);

                                            if (responseInfo.isOK()) {

                                                imageUrl = uploadBean.domain + uploadBean.path;
//
                                                Glide.with(BabyDetailsActivity.this)
                                                        .load(imageUrl)
                                                        .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                                                        .placeholder(R.mipmap.temp_pic)
                                                        .into(babyphonto);

                                                updateChildInfo();

                                            } else {
                                                showToast("图片上传失败");
                                            }

                                        }

                                    }, null);

//                        } else {
//                            showToast(Constant.showErrorMsg(uploadBean.code, BabyDetailsActivity.this));
//                        }

                    }
                }, null);
    }

    private void updateChildInfo() {

        JSONObject j = new JSONObject();
        j.put("id", id);
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("photo", imageUrl);
        j.put("birthDay", tv_birthday.getText().toString().trim());

        HttpUtil.setPostRequest("更改中...", this, Constant.WEB_ROOT + Constant.UPDATECHILDINFO,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {
                        try {

//                            org.json.JSONObject result = new org.json.JSONObject(str);
//
//                            if (result.getInt("code") == Constant.STATUS_SUCCESS) {
//
////                                sp.edit().putString(Constant.BIRTHDAY, tv_birthday.getText().toString().trim()).apply();
//
//                            } else {
//
//                                showToast(Constant.showErrorMsg(result.getInt("code"), BabyDetailsActivity.this));
////                                tv_birthday.setText(sp.getString(Constant.BIRTHDAY, ""));
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
//                            tv_birthday.setText(sp.getString(Constant.BIRTHDAY, ""));
                            showToast(Constant.NODATA);

                        }
                    }
                },null);
    }

    //裁剪图片
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_RESOULT);
    }

    /**
     * 拍照
     */
    private void getTakePhoto() {

        String cacheDir = Environment.getExternalStorageDirectory().getPath() + "/mlxCache";
        File photoFile = new File(cacheDir);
        //文件夹不存在就创建文件夹
        if (!photoFile.exists()) {
            photoFile.mkdirs();
        }
        //创建存放图片的jpg文件
        currentFile = new File(photoFile, System.currentTimeMillis() + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
        startActivityForResult(intent, TAKE_PHOTO_CODE);
    }

    /**
     * 从相册中选择
     */
    private void getFromPhotoAlbum() {

        Intent mIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(mIntent, PHOTO_ALBUM_CODE);

    }
}